import router from '@/router'
import Cache from '@/global/Cache'
import * as CacheKey from '@/global/CacheKey'
import { useVisitedRoutes } from '@/stores'


/**
 * 异步加载路由函数
 *
 * @param menus 菜单配置对象数组
 */
const loadRouters = async (menus: any) => {
  const modules = import.meta.glob('@/views/**/Index.vue')
  const routes = menus.flatMap((menu: any) => menu.children).map((item: any) => {
    // console.log(item.vue_file_path)
    const key = `/src/views/${item.vue_file_path}/Index.vue`

    const component = modules[key]
    if (!component) {
      console.error(`Component not found for route: ${item.route_path}`)
    }

    return {
      path: item.route_path,
      name: item.menu_name,
      meta: {
        title: item.menu_title,
      },
      component: () => component(), // 将 component 转换为异步函数
    }
  })

  routes.forEach((route: any) => {
    router.addRoute('Home', route)
  })
}
/**
 * 从已访问路由列表中移除指定菜单项
 *
 * @param menu 要从已访问路由列表中移除的菜单项对象
 */
export const removeVisitedRoutes = async (menu: any) => {
  const routes = useVisitedRoutes().visitedRoutes.filter((tab: any) => tab.name !== menu.name)
  useVisitedRoutes().saveState(routes)
}
/**
 * 保存访问过的路由
 *
 * @param menu 要保存的菜单对象
 */
export const saveVisitedRoutes = async (menu: any) => {
  const routes = useVisitedRoutes().visitedRoutes
  const idx = routes.findIndex((item: any) => item.name === menu.name)
  if (idx === -1) {
    routes.push({ ...menu })
    useVisitedRoutes().saveState(routes)
  }
}

export const initializeDynamicRoutes = async () => {
  const menus = Cache.get(CacheKey.MENUS_ROUTER, [])
  if (menus) {
    // console.log('已经有菜单了')
    loadRouters(menus)
  } else {
    // console.log('没有菜单')
  }
}
export default {
  name: 'index',
  tt: import.meta.env.VITE_SITE_TITLE
}
